package com.leyu.search.service;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.leyu.search.index.domain.GoodsIndexItem;
import com.leyu.search.service.SearchResult.ItemCounter;

@Service("goodsSearchService")
public class GoodsSearchServiceImpl implements GoodsSearchService {
	static Logger logger = LoggerFactory
			.getLogger(GoodsSearchServiceImpl.class);
	@Resource
	private SolrServer solrServer;

	@Override
	public SearchResult search(SearchQueryParam searchParam) {

		QueryResponse rsp = null;
		try {
			SolrQuery query = this.buildSolrQuery(searchParam);
			rsp = solrServer.query(query);
			return this.parserSearchResult(rsp, searchParam);
		} catch (SolrServerException e) {
			logger.error("search exception!", e);
		}

		return null;
	}

	private SearchResult parserSearchResult(QueryResponse rsp,
			SearchQueryParam searchParam) {
		List<GoodsIndexItem> beans = rsp.getBeans(GoodsIndexItem.class);
		SolrDocumentList docList = rsp.getResults();
		SearchResult result = new SearchResult();
		if (searchParam.pageNum == null) {
			result.setPageNo(1);
		} else {
			result.setPageNo(searchParam.pageNum);
		}
		if (searchParam.pageSize == null) {
			result.setPageSize(10);
		} else {
			result.setPageSize(searchParam.pageSize);
		}
		result.setCount(docList.getNumFound());
		result.setTotalPages(PageHelper.getTotalPages(result.getCount(),
				result.getPageSize()));
		result.setDatas(beans);
		List<FacetField> facetFieldList = rsp.getFacetFields();
		if (facetFieldList != null) {
			for (FacetField field : facetFieldList) {
				String key=field.getName();
				List<ItemCounter> counterList=new LinkedList<ItemCounter>();
				result.cateCountersMap.put(key, counterList);
				for(Count count:field.getValues()){
					ItemCounter counter=new ItemCounter();
					counter.id=Long.valueOf(count.getName());
					counter.count=count.getCount();
					counterList.add(counter);
				} 
			}
		}
		return result;
	}

	private SolrQuery buildSolrQuery(SearchQueryParam searchParam) {
		SolrQuery query = new SolrQuery();
		query.setQuery(searchParam.toAndQueryString());
		int start = 0;
		Integer pageNum = searchParam.pageNum;
		Integer pageSize = searchParam.pageSize;
		if (pageNum != null && pageSize != null) {
			start = PageHelper.getStart(pageNum, pageSize);
		}
		query.setStart(start);
		if (searchParam.sortId != null) {
			switch (searchParam.sortId.intValue()) {
			case 1:
				query.addSortField("soldQuantity", ORDER.desc);// 销量
				break;
			case 2:
				query.addSortField("price", ORDER.desc);// 价格
				break;
			case 3:
				query.addSortField("commentsCount", ORDER.desc);// 评论
				break;
			case 4:
				query.addSortField("openDateTime", ORDER.desc);// 上架时间
				break;
			}
		}
		if (searchParam.facetQuery) {
			query.setFacet(true);
			query.addFacetQuery(searchParam.toAndQueryString());
			query.addFacetField(new String[] { "areaId", "brandId",
					"priceRangeId", "systemId", "screenSizeId", "specialId" });

		}
		if (pageSize != null) {
			query.setRows(pageSize);
		}

		return query;
	}

	@Override
	public String[] getDefaultHotKeyWords() {
		String[] hotWords = { "iphone4S", "iphone5", "MAC OS", "小米手机三星手机" };
		return hotWords;
	}

	@Override
	public boolean addToIndex(GoodsIndexItem item) {
		try {
			solrServer.addBean(item);
			solrServer.commit();
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean addToIndex(Collection<GoodsIndexItem> datas) {
		try {
			solrServer.addBeans(datas);
			solrServer.commit();
			return true;
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean removeIndex(String id) {
		try {
			solrServer.deleteById(id);
			solrServer.commit();
			return true;
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean removeAllIndex() {
		try {
			solrServer.deleteByQuery("*:*");
			solrServer.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean removeIndex(List<String> ids) {
		try {
			solrServer.deleteById(ids);
			solrServer.commit();
			return true;
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}
